package com.bwie.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

@Configuration
@Order(1)
public class MyFilter implements GlobalFilter {

    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.请求
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        //2.请求路径
        String url = request.getURI().getPath();
        System.out.println("请求路径"+url);
        //3.白名单
        if(url.contains("/sendCodePhone") || url.contains("/loginPhone")){
            System.out.println("白名单"+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return chain.filter(exchange);
        }
        //4.获取请求头
        String token = request.getHeaders().getFirst("token");
        if(token == null){
            System.out.println("token为空"+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //5.解析token
        Claims claims = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();

        //6.根据token获取userId
        Integer userId = claims.get("userId", Integer.class);
        //7.根据userId获取key
        String key = "token-"+userId;
        //8.根据key获取redisToken
        String redisToken = redisTemplate.opsForValue().get(key);
        //10.判断是否为空
        if(redisToken == null){
            System.out.println("token为空"+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //9.判断两个token
        if(!redisToken.equals(token)){
            System.out.println("token值不相等"+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //11.token续期
        redisTemplate.expire(key,60, TimeUnit.MINUTES);
        //
        System.out.println("放行"+url);
        return chain.filter(exchange);
    }
}
